"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";

import { useAuth } from "@/contexts/auth-context";
import { useLoginMutation } from "@/hooks/use-login-mutation";

const loginSchema = z.object({
  identifier: z.string().min(1, "请输入登录账号"),
  password: z.string().min(6, "密码至少 6 位"),
});

type LoginFormValues = z.infer<typeof loginSchema>;

export default function LoginPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { signIn } = useAuth();
  const loginMutation = useLoginMutation();

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormValues>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      identifier: "",
      password: "",
    },
  });

  const onSubmit = handleSubmit(async (values) => {
    try {
      const result = await loginMutation.mutateAsync(values);
      signIn({
        tokens: {
          accessToken: result.accessToken,
          refreshToken: result.refreshToken,
        },
        user: result.user,
      });

      toast.success("登录成功，欢迎回来！");
      const redirectTo = searchParams?.get("from") ?? "/dashboard";
      router.replace(redirectTo);
    } catch (error) {
      const message = error instanceof Error ? error.message : "登录失败，请稍后重试";
      toast.error(message);
    }
  });

  return (
    <section className="flex flex-col items-center justify-center px-6 py-16">
      <div className="w-full max-w-sm space-y-6 rounded-lg border border-border bg-card p-6 shadow-sm">
        <div className="space-y-2 text-center">
          <h1 className="text-xl font-semibold">登录</h1>
          <p className="text-sm text-muted-foreground">使用管理员账号或分配的登录信息进入系统。</p>
        </div>

        <form className="space-y-4" onSubmit={onSubmit} noValidate>
          <div className="space-y-2">
            <label className="block text-sm font-medium text-foreground" htmlFor="identifier">
              登录账号
            </label>
            <input
              id="identifier"
              type="text"
              autoComplete="username"
              className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm transition focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary"
              placeholder="邮箱 / 手机号 / 工号"
              {...register("identifier")}
            />
            {errors.identifier ? (
              <p className="text-xs text-destructive">{errors.identifier.message}</p>
            ) : null}
          </div>

          <div className="space-y-2">
            <div className="flex items-center justify-between text-sm">
              <label className="font-medium text-foreground" htmlFor="password">
                密码
              </label>
              <Link href="#" className="text-xs text-primary hover:underline">
                忘记密码？
              </Link>
            </div>
            <input
              id="password"
              type="password"
              autoComplete="current-password"
              className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm transition focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary"
              placeholder="请输入密码"
              {...register("password")}
            />
            {errors.password ? (
              <p className="text-xs text-destructive">{errors.password.message}</p>
            ) : null}
          </div>

          <button
            type="submit"
            disabled={loginMutation.isPending}
            className="inline-flex w-full items-center justify-center gap-2 rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-70"
          >
            {loginMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
            {loginMutation.isPending ? "正在登录" : "登录"}
          </button>
        </form>

        <div className="rounded-md border border-dashed border-border bg-muted/40 p-4 text-xs text-muted-foreground">
          <p>开发提示：</p>
          <ul className="mt-2 list-disc space-y-1 pl-4">
            <li>默认管理员：`admin@example.com` / `Admin123!`。</li>
            <li>登录成功后将跳转到 `/dashboard`（后续页面待实现）。</li>
          </ul>
        </div>
      </div>
    </section>
  );
}
